
import BaseHTTPServer
import time
import sys
from data_indexer import *

HOST_NAME = '127.0.0.1' # !!!REMEMBER TO CHANGE THIS!!!
PORT_NUMBER = 4000 # Maybe set this to 9000.

last_term = None
indexer = Indexer('./handbook.txt')

class RedirectHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def __init__(self, request, client_address, server):
      BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, request, client_address, server)

    def do_GET(self):
        print self.path
        self.printCustomHTTPResponse(200)    
        like_match = re.match('/like\?(.*)', self.path)
        likes = None
        if like_match:
          likes = [int(like.strip('like=')) for like in like_match.groups()[0].split('&')]
          print likes 
        global last_term 
        term = last_term
        query_match = re.match('/search\?query=(.*)', self.path)
        if query_match:
          term = query_match.groups()[0]
          last_term = term
        print term
        results = []
        if term: 
          results = indexer.retrieve_chapters(term)[:15]

        if likes:
          print "updating", term
          update_likes(likes, results, indexer, term)
          results = indexer.retrieve_chapters(term)[:15]

        header = '''
        <html> 
        <head>
        <title>Personanlized Search</title>
        <style = "text/css">
        
        table { margin: 1em; width:30pc; border-collapse: collapse; }
        td, th { padding: .3em; border: 1px #ccc solid; }
        thead { background: #fc9; }
        tbody { background: #9cf; }
        </style>
        </head>

        <body>
        <img src="http://www.cs.sunysb.edu/~vloiwal/logo.jpg" alt="some_text"/>
        <form id="search" action="/search">
        Term: 
        <input type="text" name="query" id="query" />
        <input type="submit" value="Search!" /> 
        </form>
        <div id="result">
        <form id="likes" action="/like">
        <table class="clickon" id="clickme">
        <thead>
        <tr>
        <th>Rank</th>
        <th>Result</th>
        <th>Score</th>
        <th>Like</th>
        </tr>
        </thead>
        <tbody>%s</tbody>
        </table>
        <input type="submit" value="Update likes"/>
        </form>
        </div>

        </body>
        </html>
        '''
        result_str = ''
        cnt = 1
        for result in results:
          if result[1] > 0.0000001:
            row = '''
            <tr>
            <td>%d</td>
            <td>%s</td>
            <td>%f</td>
            <td><input type="checkbox" name="like" value="%d" /></td>
            </tr>
            ''' % (cnt, result[0], result[1], cnt)
            cnt += 1

            result_str += row 
        result_str += ''
        self.wfile.write(header % result_str)
        #self.printBrowserHeaders()
        #self.wfile.write("</body>\n</html>\n")

    def printBrowserHeaders(self):
        keys = self.headers.dict.keys()       
        self.wfile.write("\n<ul>")
        for key in keys:
            self.wfile.write("\n<li><b>" + key + "</b>: ")
            self.wfile.write(self.headers.dict[key] + "\n</li>\n")
        self.wfile.write("</ul>\n")

    def printCustomHTTPResponse(self, respcode):
        self.send_response(respcode)
        self.send_header("Content-Type", "text/html")          
        self.send_header("Server", "myHandler")
        self.end_headers()

    def log_request(self, code='-', size='-'):
        user_agent = self.headers.dict['user-agent']
        self.log_message('"%s" %s %s %s',
                         self.requestline, str(code), str(size), user_agent)

if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), RedirectHandler)
    print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)

